package com.pianke.yc.test.Data;

import android.content.Context;
import android.util.Log;

import com.pianke.yc.test.Classess.Job;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONTokener;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.nio.Buffer;
import java.util.ArrayList;

/**
 * Created by YC on 2016/4/3.
 */
public class JobJson {
    private Context mContext;
    private String mFilename;

    public JobJson(Context context, String f) {
        this.mContext = context;
        this.mFilename = f;
    }

    public void saveJob(ArrayList<Job> jobs) throws JSONException, IOException {
        JSONArray array = new JSONArray();
        for (Job j : jobs) {
            array.put(j.toJSON());
        }
        Writer writer = null;
        try {
            OutputStream out = mContext.openFileOutput(mFilename, Context.MODE_PRIVATE);
            writer = new OutputStreamWriter(out);
            writer.write(array.toString());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

    public ArrayList<Job> loadJobs() throws IOException {
        ArrayList<Job> mJobs = new ArrayList<>();
        BufferedReader reader = null;
        try {
            InputStream inputStream = mContext.openFileInput(mFilename);
            reader = new BufferedReader(new InputStreamReader(inputStream));
            StringBuffer sb = new StringBuffer();
            String str = null;
            while ((str = reader.readLine()) != null) {
                sb.append(str);
            }
            Log.i("JobJson","sb values  "+sb.toString());
            JSONArray array = (JSONArray) new JSONTokener(sb.toString()).nextValue();


            for (int i = 0; i < array.length(); i++)
                mJobs.add(new Job(array.getJSONObject(i)));
            return mJobs;
        } catch (JSONException e) {
            e.printStackTrace();
        }
        return null;
    }
}
